package ks32.crosswalk_native;


import android.app.AlarmManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.freeview.fvadpter.lightController.ILightControl;
import com.freeview.fvadpter.lightController.LightCommand;
import com.freeview.fvadpter.lightController.LightControlFactory;
import com.king.app.updater.AppUpdater;
import com.king.app.updater.UpdateConfig;
import com.king.app.updater.callback.UpdateCallback;
import com.pakdata.xwalk.refactor.XWalkView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Locale;

/**
 * web端调用app端的方法
 */
public class jsApi extends AppCompatActivity {
    private TextToSpeech textToSpeech = null;//创建自带语音对象
    public Context wcontext ;
    XWalkView wwebView;
    MediaPlayer mediaPlayer;
    public  AppUpdater mAppUpdater;
    public jsApi(Context context, XWalkView webView) {
        wcontext = context;
        wwebView = webView;
        //实例化自带语音对象
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == textToSpeech.SUCCESS) {
                    textToSpeech.setPitch(1.0f);//方法用来控制音调
                    textToSpeech.setSpeechRate(1.0f);//用来控制语速
                    //判断是否支持下面两种语言
                    int result1 = textToSpeech.setLanguage(Locale.US);
                    int result2 = textToSpeech.setLanguage(Locale.
                            SIMPLIFIED_CHINESE);
                    boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
                    boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
                    Log.i("zhh_tts", "US支持否？--》" + a +"\nzh-CN支持否》--》" + b);
                } else {
                    Log.i("zhh_tts", "数据丢失或不支持");
                }
            }
        });
    }

    @JavascriptInterface
    public void toast(String toast){
        Toast.makeText(wcontext, toast, Toast.LENGTH_SHORT).show();
    }
    /*获取版本号*/
    @JavascriptInterface
    public void  getVersionCode(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wwebView.loadUrl("javascript:getversion('"+APKVersionInfoUtils.getVersionName(wcontext)+"')");
            }
        });
    }
    /**
     * 播放语音 前提是要装个科大讯飞语音引擎3.0
     * @param data=播放的语音的内容
     */
    @JavascriptInterface
    public void TTSpeech(String data) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        textToSpeech.speak(data,//输入中文，若不支持的设备则不会读出来
                TextToSpeech.QUEUE_FLUSH, null);
    }
    /*播放背景音乐
     * type = 1 播放呼叫背景 2被呼叫的背景
     * */
    @JavascriptInterface
    public void StardialBG(String type) throws IOException {
        String fileNmae = null;
        if (type.equals("1")){
            fileNmae = "dialBG";
        }
        if (type.equals("2")){
            fileNmae = "incomingCall";
        }
        AssetManager am =  wcontext.getAssets();
        AssetFileDescriptor afd = am.openFd(fileNmae+".mp3");
        FileDescriptor fd = afd.getFileDescriptor();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(fd,afd.getStartOffset(),afd.getLength());
        mediaPlayer.prepare();//让Mediaplayer进入到准备状态
        mediaPlayer.start(); // 开始播放
        mediaPlayer.setLooping(true); // 循环播放
    }
    /*停止播放*/
    @JavascriptInterface
    public void stopBGMusic(){
        mediaPlayer.stop();
    }
    @JavascriptInterface
    /*type 0 横屏 1竖屏*/
    public void screenWwitch(String type) {
        if (type.equals("0")){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }else{
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
    @JavascriptInterface
    /*跳转到设置页*/
    public void  DxstartActivity(){
        wcontext.startActivity(new Intent(Settings.ACTION_SETTINGS));

    }
    @JavascriptInterface
    /*跳转到ip设置页*/
    public void  DxstartActivityIP(){
        wcontext.startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS));
    }
    @JavascriptInterface
    /*跳转到wift设置页*/
    public void  DxstartActivityWift(){
        wcontext.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
    }
    @JavascriptInterface
    /*跳转到设置页*/
    public void  setTime(){
        wcontext.startActivity(new Intent(Settings.ACTION_DATE_SETTINGS));
    }
    @JavascriptInterface
    /*跳转到设置音量*/
    public void  setIngs(){
        wcontext.startActivity(new Intent(Settings.ACTION_SOUND_SETTINGS));
    }
    @JavascriptInterface
    /*跳转到应用列表页*/
    public void  APPLication(){
        wcontext.startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS));
    }
    @JavascriptInterface
    /*打开相机*/
    public void  OpenXJ(){
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, 6);
    }


    /**设置系统时间
     * @param timer  "092110202025.52";   // 传入时间格式 月日时分年.秒
     */
    @JavascriptInterface
    public void InitSetTime(String timer){
        AlarmManager mAlarmManager = (AlarmManager) wcontext.getSystemService(Context.ALARM_SERVICE);
        mAlarmManager.setTimeZone("Asia/Shanghai");// Asia/Shanghai//GMT+08:00
        execSuCmd("date " + timer);
    }



    /**
     * 执行Android命令，设置系统时间
     * @param cmd  命令
     */
    public static void execSuCmd(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int aa = process.waitFor();
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String out = new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*升级app*/
    /*参考地址 https://gitee.com/jenly1314/AppUpdater/tree/master*/
    @JavascriptInterface
    public void  shengji(String mUrl){
        UpdateConfig config = new UpdateConfig();
        config.setUrl(mUrl);
        mAppUpdater = new AppUpdater(getContext(),config)
                .setUpdateCallback(new UpdateCallback() {
                    @Override
                    public void onDownloading(boolean isDownloading) {
                        Log.v("qqq4", ""+111111);
                    }

                    @Override
                    public void onStart(String url) {
                        Log.v("qqq4", ""+22222);
                    }

                    @Override
                    public void onProgress(long progress, long total, boolean isChange) {
                        int currProgress = Math.round(progress * 1.0f / total * 100.0f);
                        Log.v("qqq4", ""+currProgress);
                        wwebView.loadUrl("javascript:DownloadProgress('"+currProgress+"')");
                    }

                    @Override
                    public void onFinish(File file) {
                        Log.v("qqq4", ""+33333);
                    }

                    @Override
                    public void onError(Exception e) {
                        Log.v("qqq4", ""+44444);
                    }

                    @Override
                    public void onCancel() {
                        Log.v("qqq4", ""+55555);
                    }
                });
        mAppUpdater.start();
    }



    /**
     *  全视通 亮灯
     *
     * @param isOpen 开/关
     * @param colors 灯关颜色，参考LightCommand
     */
    @JavascriptInterface
    public void lightRoomTopControl(boolean isOpen, String colors) {
        LightControlFactory controlFactory = new LightControlFactory();
        ILightControl topLedLight = controlFactory.getTopLedLightControl();//顶部LED灯光控制
        /*亮红灯*/
        if(colors.equals("7")){
            topLedLight.setColor(LightCommand.LIGHT_COMMAND_ROOM_RED);
        }
        /*亮绿灯*/
        if(colors.equals("8")){
            topLedLight.setColor(LightCommand.LIGHT_COMMAND_ROOM_GREEN);
        }
        /*亮黄灯*/
        if(colors.equals("9")){
            topLedLight.setColor(LightCommand.LIGHT_COMMAND_ROOM_YELLOW);
        }
        /*亮蓝灯*/
        if(colors.equals("10")){
            topLedLight.setColor(LightCommand.LIGHT_COMMAND_ROOM_BLUE);
        }
        if (isOpen) {
            topLedLight.Light_open();
        } else {
            topLedLight.Light_close();
        }
    }
    // 版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }
    public Context getContext(){
        return wcontext;
    }
    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }




}
